<?php
/**
 * Created by PhpStorm.
 * User: mars
 * Date: 2018/8/22
 * Time: 下午8:06
 */

namespace api\controllers;


use api\models\Photo;
use api\models\User;
use common\helpers\ImgExifHelper;
use common\helpers\Util;
use Exception;
use yii\helpers\Url;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\Response;
use Yii;


class PhotoController extends ARBaseController
{

    const TYPE_HOT = 1;
    const TYPE_LATS = 2;
    const TYPE_ATTENTION = 3;
    public $modelClass = 'api\models\Photo';

    public function getUser()
    {
        return User::findIdentityByAccessToken(\Yii::$app->request->getHeaders()->get('access-token'));
    }

    public function actions()
    {
        $actions = parent::actions(); // TODO: Change the autogenerated stub
        unset($actions['create']);

        return ArrayHelper::merge($actions,
            [
                'create',
            ]);
    }

    /**
     * @return array
     * @throws \yii\base\InvalidConfigException
     */
    public function actionCreate()
    {


//        return 'fuck!';
        $model = new Photo();
        $model->load(Yii::$app->request->getBodyParams(), '');
        $model->uid = $this->user->id;
//        if (Util::handleImgUpload($model, 'img', true, '@photo', []) != false) {
//            Yii::$app->response->statusCode = 422;
//
//            return ['error' => "图片上传失败"];
//        }
//		var_dump(Url::toRoute(''.$model->img));
//        $fp             = fopen(Url::to('../' . $model->img), 'rb');
//        $exif           = ImgExifHelper::getExif($fp);
//        $model->iso     = (string)$exif['iso'];
//        $model->make    = $exif['make'];
//        $model->model   = $exif['model'];
//        $model->flength = (double)$exif['flength'];
//        $model->fnumber = $exif['fnumber'];
//        $model->exposer = $exif['exposer'];
        $imgfile = Util::base64_upload($model->img,Yii::getAlias('@photo'));
//        return $imgfile;
        if($imgfile != false){
            $model->img = $imgfile;
        }else{
            $model->img = "fail";
        }

        if ($model->save()) {
            return ['data' => $model];
        } else {
            $model->validate();
            Yii::$app->response->statusCode = 422;

            return ['error' => "上传失败", 'errors' => $model->errors];
        }
    }


    //查询（拓展成根据相机信息查询的）
    public function actionSearch()
    {
        return Photo::find()
                    ->where([
                        'like',
                        'brife',
                        \Yii::$app->request->post('keyword')
                    ])
                    ->all();
    }


    public function actionCollect($id)
    {

        return Photo::find()
                    ->where([
                        'in',
                        'id',
                        (new Query())
                            ->select('pid')
                            ->from('collect')
                            ->where(['uid' => $id])
                    ])
                    ->andWhere(['status' => 1])
                    ->all();

    }

    public function actionMine($id)
    {
        return Photo::find()
                    ->where(['uid' => $id])
                    ->orderBy('created_at DESC')
                    ->all();
    }

    public function actionPush($type)
    {
        $msg  = null;
        $user = User::findIdentityByAccessToken(\Yii::$app->request->getHeaders()->get('access-token'));
        switch ($type) {
            case  self::TYPE_HOT :
                $msg = [
                    'type' => self::TYPE_HOT,
                    'data' => Photo::find()
                                   ->leftJoin('(select pid,count(id) num from `like`group by pid) pl', 'pid = id')
                                   ->Where(['status' => 1])
                                   ->orderBy('num DESC')
                                   ->all(),
                ];
                break;
            case self::TYPE_LATS:
                $msg = [
                    'type' => self::TYPE_LATS,
                    'data' => Photo::find()
                                   ->Where(['status' => 1])
                                   ->orderBy('updated_at DESC')
                                   ->all(),
                ];
                break;
            case self::TYPE_ATTENTION :
                $msg = [
                    'type' => self::TYPE_ATTENTION,
                    'data' => Photo::find()
                                   ->where([
                                       'in',
                                       'uid',
                                       (new Query())
                                           ->select('ccid')
                                           ->from('fans')
                                           ->where(['cid' => $user->id])
                                   ])
                                   ->andWhere(['status' => 1])
                                   ->all(),
                ];
                break;
        }

        return $msg;
    }


}